import {CLEAR_INDEX_DATA, GET_INDEX_DATA} from '../../config/ActionType'
import {fetch, API_GET_INDEX_DATA} from '../../config/Api'
import {showEmptyStation} from '../../global/actions/'

export const getIndexData = data => ({
  type: GET_INDEX_DATA,
  payload: {home: data}
})

export function fetchIndexData() {
  return (dispatch, getState) => fetch(API_GET_INDEX_DATA)(dispatch, getState).then(json => {
    if (json.success) {
      dispatch(getIndexData(json.data))
    } else {
      dispatch(showEmptyStation(json.message))
    }
  })
}

export const clearIndexData = () => ({type: CLEAR_INDEX_DATA})

export const actions = {
  fetchIndexData,
  clearIndexData
}

// Reducers
export const ACTION_HANDLERS = {
  [GET_INDEX_DATA]: (state, action) => ({...state, data: action.payload.home, fetching: false}),
  [CLEAR_INDEX_DATA]: state => ({...state, data: undefined})
}

const initialState = {data: undefined}

export default function(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}
